package com.sky.controller.admin;


import cn.hutool.core.util.ObjectUtil;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * C端新增地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    public Result addAddressBook(@RequestBody AddressBook addressBook) {
        log.info("新增地址:{}", addressBook);
        addressBookService.addAddressBook(addressBook);
        return Result.success();
    }


    /**
     * C端查询当前登录用户的所有地址信息
     *
     * @return
     */
    @GetMapping("list")
    public Result<List<AddressBook>> findAddressBook() {
        log.info("查询当前登录用户的所有地址信息");
        List<AddressBook> addressBooks = addressBookService.findAddressBook();
        return Result.success(addressBooks);
    }

    /**
     * C端查询默认地址
     *
     * @return
     */
    @GetMapping
    public Result<AddressBook> findAddressBookByDefault() {
        log.info("C端查询默认地址");
        AddressBook addressBook = addressBookService.findAddressBookByDefault();
        if (ObjectUtil.isNotNull(addressBook)) {
            return Result.success(addressBook);
        }
        return Result.error("没有查询到默认地址");
    }

    /**
     * C端设置默认地址
     *
     * @return
     */
    @PutMapping("default")
    public Result updateDefault(@RequestBody AddressBook addressBook) {
        log.info("C端设置默认地址:{}", addressBook);
        addressBookService.updateDefault(addressBook);
        return Result.success();
    }


    /**
     * C端根据id修改地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    public Result updateAddressBook(@RequestBody AddressBook addressBook) {
        log.info("C端根据id修改地址:{}", addressBook.getId());
        addressBookService.updateAddressBook(addressBook);
        return Result.success();
    }

    /**
     * C端根据id查询地址
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public Result deleteById(Long id) {
        addressBookService.deleteById(id);
        return Result.success();
    }

}
